package integral

import (
	"context"
	"strings"

	"mall/common/jwt"
	"mall/common/resultx"
	"mall/service/backend/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/setting/rpc/settingclient"
	"mall/service/user/rpc/userclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type ExecIntegralTaskLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewExecIntegralTaskLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExecIntegralTaskLogic {
	return &ExecIntegralTaskLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ExecIntegralTaskLogic) ExecIntegralTask(req *types.IntegralTaskLogInfo) (*types.BaseMsgResp, error) {
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}
	if req.TaskId == nil || *req.TaskId == 0 {
		return nil, resultx.NewErrCode(resultx.INTEGRAL_TASK_TASK_ID_REQUIRED)
	}
	if req.Integrals == nil || *req.Integrals == 0 {
		return nil, resultx.NewErrCode(resultx.INTEGRAL_TASK_INTEGRALS_REQUIRED)
	}
	task, err := l.svcCtx.SettingRpc.GetIntegralTaskById(l.ctx, &settingclient.IntegralTaskDetailReq{
		Id: req.TaskId,
	})
	if err != nil {
		return nil, err
	}
	if task.Points == nil || *req.Integrals != *task.Points {
		return nil, resultx.NewErrCode(resultx.INTEGRAL_TASK_INTEGRALS_INVALID)
	}
	if task.RuleName == nil || len(strings.TrimSpace(*task.RuleName)) == 0 {
		return nil, resultx.NewErrCode(resultx.INTEGRAL_TASK_NAME_REQUIRED)
	}
	res, err := l.svcCtx.UserRpc.ExecIntegralTaskLog(l.ctx, &userclient.IntegralTaskInfo{
		UserId:        pointy.GetPointer(userId),
		TaskId:        req.TaskId,
		TaskName:      task.RuleName,
		TaskSlug:      task.RuleSlug,
		TaskFrequency: task.Frequency,
		Gems:          req.Gems,
		Growth:        req.Growth,
		Integrals:     task.Points,
		Status:        req.Status,
	})
	if err != nil {
		return nil, err
	}
	return &types.BaseMsgResp{
		Msg: res.Msg,
	}, err
}
